package com.millstein.interceptor;

import cn.hutool.core.util.StrUtil;
import com.millstein.context.UserAuthorization;
import com.millstein.enums.BizCodeEnum;
import com.millstein.model.LoginUser;
import com.millstein.util.CommonUtils;
import com.millstein.util.JsonData;
import com.millstein.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description:
 * @author: tsing
 * @create: 2021-09-13 16:36
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.解密token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }

        if (StrUtil.isBlank(token)) {
            CommonUtils.wrapperResponseAsJson(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
            return false;
        }

        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            CommonUtils.wrapperResponseAsJson(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_TOKEN_IS_ILLEGAL));
            return false;
        }

        // 构建登录对象
        LoginUser loginUser = new LoginUser(claims);

        // 保存登录的用户数据到threadLocal中去
        UserAuthorization.setUserContext(loginUser);
        return true;
    }
}
